import { ExceptionFilter, Catch, ArgumentsHost } from '@nestjs/common';
import { HttpException } from '@nestjs/common';

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: any, host: ArgumentsHost) {
    const ctx: any = host.switchToHttp(); // 获取请求上下文
    const response = ctx.getResponse(); // 获取 response 对象
    const request = ctx.getRequest(); // 获取 request 对象
    const status = exception.getStatus(); // 获取异常的状态码
    let messageMap = {
      401: 'token失效'
    }
    const messageItem = messageMap[status] ? messageMap[status] : ''
    const messageTxt = typeof exception.response.message === 'object' ? exception.response.message[0] : exception.response.message
    response.status(status).json({
      message: messageItem || messageTxt,
      code: status,
      timestamp: new Date().toISOString(),
      path: request.url,
    });
  }
}

